package com.atguigu.PracticalProject.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.PracticalProject.app.BaseAppV1;
import com.atguigu.PracticalProject.bean.UserRegisterBean;
import com.atguigu.PracticalProject.common.Constant;
import com.atguigu.PracticalProject.util.AtguiguUtil;
import com.atguigu.PracticalProject.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class DwsUserUserRegisterWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsUserUserRegisterWindow().init(4001, 2, "DwsUserUserRegisterWindow", Constant.TOPIC_DWD_USER_REGISTER);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 加水印
        SingleOutputStreamOperator<JSONObject> waterMarkStream = addWaterMark(stream);

        //2. 开窗聚合
        SingleOutputStreamOperator<UserRegisterBean> resultStream = windowAndAgg(waterMarkStream);

        //3. 写出到doris
        writeToDoris(resultStream);
    }

    private void writeToDoris(SingleOutputStreamOperator<UserRegisterBean> resultStream) {
        resultStream
            .map(bean -> {
                SerializeConfig config = new SerializeConfig();
                config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                return JSON.toJSONString(bean, config);
            })
            .addSink(FlinkSinkUtil.getDorisSink("gmall2022.dws_user_user_login_window"));
    }

    private SingleOutputStreamOperator<UserRegisterBean> windowAndAgg(SingleOutputStreamOperator<JSONObject> waterMarkStream) {
        return waterMarkStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L))) // 开窗
            .aggregate(                                                 // 聚合
                new AggregateFunction<JSONObject, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }

                    @Override
                    public Long add(JSONObject jsonObject, Long acc) {
                        acc += 1;
                        return acc;
                    }

                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }

                    @Override
                    public Long merge(Long aLong, Long acc1) {
                        return null;
                    }
                },
                new AllWindowFunction<Long, UserRegisterBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<Long> values, Collector<UserRegisterBean> collector) throws Exception {
                        for (Long value : values) {
                            String stt = AtguiguUtil.toDateTime(window.getStart());
                            String edt = AtguiguUtil.toDateTime(window.getEnd());
                            String curDate = AtguiguUtil.toDate(window.getStart());
                            UserRegisterBean userRegisterBean = new UserRegisterBean(
                                stt,
                                edt,
                                curDate,
                                value
                            );
                            collector.collect(userRegisterBean);
                        }
                    }
                }
            );
    }

    private SingleOutputStreamOperator<JSONObject> addWaterMark(DataStreamSource<String> stream) {
        return stream.map(JSON::parseObject)
            .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forMonotonousTimestamps().withTimestampAssigner(
                new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject jsonObject, long l) {
                        return jsonObject.getLong("ts") * 1000L;
                    }
                }
            ));
    }
}
